<template>
    <div class="custom-select" v-clickOutside="closeDropdown" :style="{ width }">
      <div class="custom-select__wrapper">
        <input
          ref="inputRef"
          type="text"
          :value="modelValue"
          @input="handleInput"
          @focus="handleFocus"
          @click="handleClick"
          @keydown.enter="handleEnter"
          @keydown.esc="closeDropdown"
          @keydown.up.prevent="handleKeyUp"
          @keydown.down.prevent="handleKeyDown"
          :placeholder="placeholder"
          :disabled="disabled"
          class="custom-select__input"
          :class="{ 
            'is-focus': showDropdown,
            'is-disabled': disabled 
          }"
        />
        <span 
          v-if="modelValue && !disabled" 
          class="custom-select__clear" 
          @click.stop="clearValue"
        >×</span>
      </div>     
      <div v-show="showDropdown" class="custom-select__dropdown text-14px">
        <div 
          v-for="(item, index) in displayOptions" 
          :key="item.value"
          class="custom-select__option"
          @click="selectOption(item)"
          :class="{ 
            'is-active': modelValue === item.value,
            'is-disabled': item.disabled,
            'is-highlighted': currentIndex === index
          }"
        >
          {{ item.label }}
        </div>
        <div v-if="displayOptions.length === 0" class="custom-select__empty">
          
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  interface Option {
    label: string
    value: string | number
    disabled?: boolean
  }
  const props = defineProps({
    modelValue: {
      type: [String, Number],
      default: ''
    },
    options: {
      type: Array as () => Option[],
      default: () => []
    },
    placeholder: {
      type: String,
      default: '选择'
    },
    width: {
      type: String,
      default: '100%'
    },
    filterable: {
      type: Boolean,
      default: true
    },
    remote: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  })
  
  const emit = defineEmits(['update:modelValue'])
  const inputRef = ref<HTMLInputElement | null>(null)
  const showDropdown = ref(false)
  const searchText = ref('') // 搜索框输入的值
  const isUserInput = ref(false) // 是否是用户输入
  const currentIndex = ref(-1) // 当前选中的索引
  
  // 监听 modelValue 变化
  watch(() => props.modelValue, (newVal) => {
    if (!isUserInput.value) {
      if (newVal !== undefined && newVal !== null) {
        const option = props.options.find(item => item.value === newVal)
        if (option) {
          searchText.value = option.label
        } else {
          searchText.value = String(newVal)
        }
      } else {
        searchText.value = ''
      }
    }
  }, { immediate: true })
  
  // 显示选项列表 - 修改为只依赖搜索文本，不再依赖isUserInput
  const displayOptions = computed(() => {
    if (!searchText.value || !props.filterable) {
      return props.options
    }
    
    const search = searchText.value.toLowerCase();
    return props.options.filter(item => {
      const itemLabel = item.label.toLowerCase()
      const itemValue = String(item.value).toLowerCase()
      
      return itemLabel.includes(search) || itemValue.includes(search)
    })
  })
  
  // 处理输入 - 实时响应
  const handleInput = (e: Event) => {
    const target = e.target as HTMLInputElement
    isUserInput.value = true
    searchText.value = target.value
    emit('update:modelValue', target.value)
  }
  
  // 处理聚焦 - 修改聚焦逻辑，保持过滤状态
  const handleFocus = () => {
    console.log("聚焦中",111);
    if (props.disabled) return
    showDropdown.value = true
    // 不再重置isUserInput，保持过滤状态
    currentIndex.value = -1
  }
  
  // 选择选项
  const selectOption = (item: Option) => {
    if (item.disabled) return
    isUserInput.value = false
    emit('update:modelValue', item.value)
    searchText.value = item.label
    showDropdown.value = false
    currentIndex.value = -1
  }
  
  // 处理点击输入框
  const handleClick = () => {
    if (props.disabled) return
    showDropdown.value = true
    if (inputRef.value) {
      const length = inputRef.value.value.length
      inputRef.value.setSelectionRange(length, length)
    }
  }
  
  // 清空值
  const clearValue = () => {
    emit('update:modelValue', '')
    searchText.value = ''
    showDropdown.value = false
    currentIndex.value = -1
  }
  
  // 关闭下拉框
  const closeDropdown = () => {
    showDropdown.value = false
    // 不重置isUserInput，只有在清空或选择时才重置
    currentIndex.value = -1
  }
  
  // 键盘事件处理
  const handleKeyUp = () => {
    if (displayOptions.value.length) {
      currentIndex.value = currentIndex.value <= 0 ? displayOptions.value.length - 1 : currentIndex.value - 1
    }
  }
  
  const handleKeyDown = () => {
    if (displayOptions.value.length) {
      currentIndex.value = currentIndex.value >= displayOptions.value.length - 1 ? 0 : currentIndex.value + 1
    }
  }
  const handleEnter = () => {
    if (currentIndex.value > -1) {
      selectOption(displayOptions.value[currentIndex.value])
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .custom-select {
    position: relative;
    display: inline-block;
    
    &__wrapper {
      position: relative;
      width: 100%;
    }
    
    &__input {
      width: 100%;
      height: 32px;
      padding: 0 30px 0 12px;
      background-color: #042252;
      border: 1px solid transparent;
      border-radius: 4px;
      outline: none;
      transition: all 0.2s;
      color: #ffffff;
      font-size: 14px;
      
      &::placeholder {
        color: rgba(255, 255, 255, 0.6);
      }
      
      &.is-disabled {
        background-color: rgba(4, 34, 82, 0.7);
        cursor: not-allowed;
        color: rgba(255, 255, 255, 0.4);
      }
    }
    
    &__clear {
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      color: rgba(255, 255, 255, 0.6);
      cursor: pointer;
      font-size: 16px;
      width: 16px;
      height: 16px;
      line-height: 16px;
      text-align: center;
      
      &:hover {
        color: #ffffff;
      }
    }
    
    &__dropdown {
      position: absolute;
      top: 100%;
      left: 0;
      width: 100%;
      max-height: 200px; /* 增加高度，显示更多选项 */
      overflow-y: auto;
      background-color: #042252;
      border: 1px solid transparent;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
      z-index: 9999;
      margin-top: 4px;
  
      &::-webkit-scrollbar {
        width: 6px;
      }
  
      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.2);
        border-radius: 3px;
      }
  
      &::-webkit-scrollbar-track {
        background: transparent;
      }
    }
    
    &__option {
      padding: 8px 12px;
      cursor: pointer;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color: #ffffff;
      
      &:hover {
        background-color: #0a3573 !important;
      }
      
      &:not(:hover) {
        background-color: transparent !important;
      }
      
      &.is-active {
        background-color: #0d4494 !important;
        color: #ffffff !important;
      }
      
      &.is-disabled {
        color: #8c8c8c !important;
        cursor: not-allowed;
        
        &:hover {
          background-color: transparent !important;
        }
      }
      
      &.is-highlighted {
        background-color: #0a3573 !important;
      }
    }
    
    &__empty {
      padding: 8px 12px;
      color: rgba(255, 255, 255, 0.6);
      text-align: center;
    }
  }
  </style>